package org.yunai.swjg.server.module.formation.vo;

import org.yunai.swjg.server.entity.FormationEntity;
import org.yunai.swjg.server.module.formation.FormationMapper;
import org.yunai.swjg.server.module.player.vo.Player;
import org.yunai.yfserver.persistence.PersistenceObject;
import org.yunai.yfserver.spring.BeanManager;
import org.yunai.yfserver.util.StringUtils;

/**
 * 阵形,创建角色的时候就创建了。
 * User: yunai
 * Date: 13-5-30
 * Time: 上午9:00
 */
public class Formation implements PersistenceObject<Integer, FormationEntity> {

    private static FormationMapper formationMapper;
    static {
        formationMapper = BeanManager.getBean(FormationMapper.class);
    }

    /**
     * 玩家信息
     */
    private Player player;
    /**
     * 阵形
     */
    private int[] positions;
    /**
     * 可携带伙伴，包括主角本身
     */
    private int max;

    public Formation(Player player) {
        this.player = player;
    }

    @Override
    public Integer getId() {
        return player.getId();
    }

    @Override
    public void fromEntity(FormationEntity entity) {
        this.positions = StringUtils.splitInt(entity.getPositions(), ",");
        this.max = entity.getMax();
    }

    @Override
    public FormationEntity toEntity() {
        FormationEntity entity = new FormationEntity();
        entity.setId(player.getId());
        entity.setPositions(StringUtils.buildString(positions, ","));
        entity.setMax(max);
        return entity;
    }

    @Override
    public boolean isInDB() {
        return true;
    }

    @Override
    public void setInDB(boolean inDB) {
        throw new UnsupportedOperationException("该对象在角色创建时，同步插入，所以该方法不会调用！");
    }

    @Override
    public Integer getUnitId() {
        return player.getId();
    }

    public int getMax() {
        return max;
    }

    public void setMax(int max) {
        this.max = max;
    }

    // ==================== 业务方法BEGIN ====================
    public void load() {
        FormationEntity entity = formationMapper.select(player.getId());
        fromEntity(entity);
    }

    public boolean isFull() {
        return player.getOnline().getPlayer().getPartnerDiary().recruitCount() + 1 >= max;
    }
}
